<?php
/**
 * Description of ListarViewGenerator
 *
 * @author Magno
 */
class ListarViewGenerator extends ViewGenerator{

    public function __construct($tableMeta, $viewParams) {
        parent::__construct($tableMeta, $viewParams, Constantes::$TEMPLATES_VIEW_DIR."listar.bloum");
    }

    public function generate() {
        parent::generateNames();
        $this->generateAttValues();
        return $this->templateView;
    }

    public function generateAttValues(){
        $this->generateAttValuesParam($this->tableMeta);
    }

    public function generateAttValuesParam($table){

        $tableName = $table->getName();
        $attributes = $table->getAttributes();
        $attrsKeys = array_keys($attributes);

        $attBuscaJs = "";
        $attBuscaJsParam = "";

        for ($i = 0; $i < count($attrsKeys); $i++) {
            $att = $attributes[$attrsKeys[$i]];
            $name = $att->getName();

            if(!$att->isImportant() || ($att->isPrimaryKey() && !$att->isForeignKey()))  continue;          

            if(!$att->isForeignKey()){
                $attBuscaJs .= 'var '.$name.' = $("#'.$name.'").val();'."\n\t\t";
                $attBuscaJsParam .= $name.' : '.$name.','."\n\t\t\t\t";
            }
            else{

                $tbFkName = str_replace("ID", "", $name);
                $fks = $table->getFKReferences();
                $fkMeta = null;
                foreach ($fks as $fk) {
                    foreach ($fk->getAttributes() as $fkAtt) {
                        if(strcmp(strtolower($fkAtt->getName()), strtolower($tbFkName."ID")) == 0){
                            $fkMeta = $fk;
                            break;
                        }
                    }
                    if($fkMeta != null) break;
                }
                if($fkMeta == null)
                    throw new Exception ("Tabela (".$tbFkName.") Referenciada Na Herança com (".$this->tableMeta->getName().") Não Encontrada!!!");

                if($fkMeta->isExtends())
                    $this->generateAttValuesParam ($fkMeta->getTableReference());

                $tbReference = $fkMeta->getTableReference()->getName();
                
                if(strcmp($fkMeta->getTypeForm(), Constantes::$TYPE_FORM_COMBO) == 0){
                    $attBuscaJs .= 'var '.$name.' = $("#'.$name.'").val();'."\n\t\t";
                    $attBuscaJsParam .= $name.' : '.$name.','."\n\t\t\t\t";
                }
            }

        }

        $this->templateView = str_replace(Constantes::$TPL_VIEW_LISTAR_ATT_BUSCA_JS_PARAM, $attBuscaJsParam, $this->templateView);
        $this->templateView = str_replace(Constantes::$TPL_VIEW_LISTAR_ATT_BUSCA_JS, $attBuscaJs, $this->templateView);

    }

    public function generateFile($generate = true){
        if($generate)
            $this->generate();
        parent::generateFile("listar");
    }
}
?>
